package com.jianjunhuang.demo.servicedemo;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button startBtn;
    private Button stopBtn;
    private Button bindBtn;
    private Button unBindBtn;

    private Intent serviceIntent;
    private ServiceConnection connection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startBtn = findViewById(R.id.start_btn);
        stopBtn = findViewById(R.id.stop_btn);
        bindBtn = findViewById(R.id.bind_btn);
        unBindBtn = findViewById(R.id.unbind_btn);

        startBtn.setOnClickListener(this);
        stopBtn.setOnClickListener(this);
        bindBtn.setOnClickListener(this);
        unBindBtn.setOnClickListener(this);
        serviceIntent = new Intent(MainActivity.this, MService.class);
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                MService.MBinder binder = (MService.MBinder) service;
                binder.show();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_btn: {
                startService(serviceIntent);
                break;
            }
            case R.id.stop_btn: {
                stopService(serviceIntent);
                break;
            }
            case R.id.bind_btn: {
                bindService(serviceIntent, connection,Service.BIND_AUTO_CREATE);
                break;
            }
            case R.id.unbind_btn: {
                unbindService(connection);
                break;
            }
        }
    }
}
